<template>
  <div>
    <div style="padding: 16px 16px 0px; background-color: #fff; margin-bottom: 16px">
      <el-descriptions>
        <template v-if="type == '2'">
          <el-descriptions-item label="微信群名称:"
            ><span style="color: #333; font-weight: bold">{{ weChatGroup.wxGroupName }}</span></el-descriptions-item
          >
          <el-descriptions-item label="关联网格经理:"
            ><span style="color: #333; font-weight: bold">{{
              weChatGroup.managerDtoList?.map((e) => e.managerName)?.join('、')
            }}</span></el-descriptions-item
          >
          <el-descriptions-item label="关联片区/村社:"
            ><span style="color: #333; font-weight: bold">{{
              weChatGroup.communityDtoList?.map((e) => e.communityName)?.join('、')
            }}</span></el-descriptions-item
          >
        </template>
      </el-descriptions>
    </div>
    <BaseForm
      ref="searchForm"
      type="search"
      :items="formItems"
      v-model:form="searchParams"
      @search="handleSearch"
      labelWidth="100px"
    >
    </BaseForm>

    <BaseTable
      ref="baseTable"
      :getTableDataFn="wxUserService.getWxUserList"
      :searchParams="searchParams"
      :serial="true"
    >
      <template #select>
        <el-table-column type="selection" width="55" />
      </template>
      <el-table-column prop="wxUserId" label="微信id" />
      <el-table-column prop="wxCode" label="微信号" />
      <el-table-column prop="wxUserName" label="微信昵称" />
      <el-table-column prop="wxUserRemark" label="群昵称">
       <!--  <template #default="scope">
          {{ scope.row.wxUserRemark || scope.row.wxUserName }}
        </template> -->
      </el-table-column>
      <el-table-column prop="url" label="头像">
        <template #default="scope">
          <el-image
            :preview-teleported="true"
            :preview-src-list="[scope.row.url || defaultUrl]"
            style="width: 50px; height: 50px"
            :src="scope.row.url || defaultUrl"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="微信电话" />
      <el-table-column prop="isSpecial" label="是否特殊人员">
        <template #default="scope">
          <el-text v-if="scope.row.isSpecial === 1">是</el-text>
          <el-text v-else>否</el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" v-if="scope.row.isSpecial === 1" @click="handleSetting(scope.row)"
            >取消设为特殊人员
          </el-button>
          <el-button v-else type="text" @click="handleSetting(scope.row)">设为特殊人员</el-button>
        </template>
      </el-table-column>
      <template v-slot:batchBtn>
        <el-button type="default" @click="download"
          ><el-icon> <Bottom></Bottom> </el-icon>导出</el-button
        >
        <el-button type="default" @click="handleSettSpecail(1)">设为特殊人员</el-button>
        <el-button type="default" @click="handleSettSpecail(2)">取消特殊人员</el-button>
      </template>
    </BaseTable>
  </div>
</template>

<script setup lang="ts">
import openMsgBox from '@/hooks/messageBox.js';
import { basicConfigService } from '@/api/basicConfig';
import { wxUserService } from '@/api/wxUser';
import { getRobotState } from '@/hooks/getStateName';
import defaultUrl from '@/assets/tx.png';
import type { FormInstance } from 'element-plus';

const communityList = ref([]);

const getAllCommunity = () => {
  let options = [];
  basicConfigService.getAllCommunity({ data: {} }).then((res) => {
    let data = res.data.map((e) => {
      return {
        label: e.communityName,
        value: e.communityId,
      };
    });
    options.push(...data);
  });
  communityList.value = options;
};
const router = useRouter();
const bizId = computed(() => {
  return router.currentRoute.value.query.bizId?.toString();
});
const type = computed(() => {
  return router.currentRoute.value.query.type?.toString();
});
const formItems = ref([
  {
    name: '微信号',
    key: 'wxCode',
    type: 'input',
  },
  {
    name: '微信昵称',
    key: 'wxUserName',
    type: 'input',
  },
  {
    name: '群昵称',
    key: 'wxUserRemark',
    type: 'input',
  },
  {
    name: '是否特殊人员',
    key: 'isSpecial',
    type: 'select',
    options: [
      {
        label: '是',
        value: 1,
      },
      {
        label: '否',
        value: 0,
      },
    ],
  },

  /*   {
      name: '群昵称',
      key: 'wxUserRemark',
      type: 'input',
    }, */

  // {
  //   name: '微信电话',
  //   key: 'phone',
  //   type: 'input',
  // },
]);

const searchParams = ref({
  wxUserId: '',
  wxUserName: '',
  wxUserRemark: '',
  isSpecial: '',
  // phone: '',
  bizId: bizId.value,
});
const form = ref({
  realUserName: '',
  realPhone: '',
  realAddressInfoList: [],
  customerId: '',
  wxUserId: '',
});
const loading = ref(false);
const weChatGroup = window.localStorage.getItem('weChatGroup')
  ? JSON.parse(window.localStorage.getItem('weChatGroup'))
  : {};
onMounted(() => {
  if (type.value == '2') {
  }
});

const baseTable = ref(null);
const sortTablekey = ref(1);

const handleSearch = (data = { sort: undefined }, e = '') => {
  if (e != 'sort') sortTablekey.value = 0;
  baseTable.value.handleSearch({
    ...searchParams.value,
    bizId: bizId.value,
    updateTimeOrder: data?.sort,
  });
};

const handleSetting = async (row) => {
  const message = row.isSpecial ? '取消设为特殊人员确认' : '设为特殊人员确认';
  ElMessageBox.confirm('是否确认？', message, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      handleConfirm(row);
    })
    .catch(() => {
      // console.log('取消');
    });
};
const handleConfirm = async (row: any) => {
  const params = {
    data: {
      wxGroupCode: bizId.value,
      wxUserIds: [row.wxUserId],
      isSpecial: row.isSpecial ? 0 : 1,
    },
  };
  const res = await basicConfigService.setSpecialStatus(params);
  if (res.success) {
    await handleSearch();
  }
};

const download = async () => {
  // 下载
  console.log('下载');
  basicConfigService
    .wxUserDownload({
      data: {
        ...searchParams.value,
      },
    })
    .then((res) => {
      var blob = new Blob([res]);
      let url = window.URL.createObjectURL(blob);
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', '微信成员列表.xls');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
};

const handleSettSpecail = async (type: number) => {
  const ids = baseTable.value.multipleSelection.map((e) => e.wxUserId);
  if (!ids.length) {
    ElMessage({
      message: '请至少选择一条数据',
      type: 'warning',
    });
    return;
  }
  const message = type === 2 ? '取消设为特殊人员确认' : '设为特殊人员确认';
  ElMessageBox.confirm('是否确认？', message, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 1 设为特殊人员 2 取消特殊人员

      const params = {
        data: {
          wxGroupCode: bizId.value,
          wxUserIds: ids,
          isSpecial: type === 1 ? 1 : 0,
        },
      };
      const res = await basicConfigService.setSpecialStatus(params);
      if (res.success) {
        await handleSearch();
      }
    })
    .catch(() => {
      // console.log('取消');
    });
};
</script>

<style lang="less" scoped></style>
